package cn.itsource.org.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.itsource.basic.domain.AjaxResult;
import cn.itsource.basic.domain.LoginVO;
import cn.itsource.basic.domain.UserInfo;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.User;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.org.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisService redisService;

    @Override
    public AjaxResult exist(String phone) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("phone", phone);
        User user = userMapper.selectOneByExample(example);
        String s = "[1][3,4,5,7,8][0-9]{8}";

        if(user != null){
            return AjaxResult.setMsg("手机号已存在");
        }else if(phone.matches(s)){
            return AjaxResult.setMsg("请输出正确的手机号");
        }
        return AjaxResult.me();
    }

    @Override
    public AjaxResult login(User user) {
        User login = userMapper.login(user);
        if(Objects.isNull(login)) throw  new RuntimeException("用户不存在");
        String salt = login.getSalt();
        String passwordMD5 = MD5.create().setSalt(salt.getBytes()).digestHex(user.getPassword());
        if(!Objects.equals(login.getPassword(), passwordMD5)){
            return AjaxResult.setMsg("用户不存在");
        }
        UserInfo userInfo = new UserInfo();
        BeanUtil.copyProperties(login,userInfo);
        String uuid = IdUtil.fastSimpleUUID();
        redisService.setStringKeyAndValue(uuid, login, 30);
        return AjaxResult.setResult(new LoginVO(uuid, userInfo));
    }

}
